import { store } from "@ice/stark-data";
import getBasename from "@ice/stark-app/lib/getBasename";
// import root from '../layouts/MenuList.vue';
const _modules = import.meta.glob("../pages/**/*.vue"); // 这是vite才能使用的引入方式
/**
 *
 * @param {*} routes
 * @param {*} deleteParam 需要截取掉主应用的name值 eg:将"/basic-facilities/query" -> "/query"
 * @returns
 */

function getAsyncRoutes(routes, deleteParam) {
  if (routes) {
    const res = [];
    const keys = ["path", "name", "children", "redirect", "meta", "hidden"];
    routes.forEach(item => {
      const newItem = {};
      if (item.component) {
        if (item.component === "root") {
          // newItem.component = root
        } else {
          newItem.component = _modules[`../${item.component}`];
        }
      }
      for (const key in item) {
        if (keys.includes(key)) {
          newItem[key] = item[key];
        }

        if (key == "activePath") {
          newItem.path = item.activePath.replace(deleteParam, "");
        }
      }

      if (newItem.children && newItem.children.length) {
        newItem.children = getAsyncRoutes(item.children, deleteParam);
      }
      res.push(newItem);
    });

    return res;
  }
}

export function addRoutes(routes) {
  return routes.reduce((result, item) => {
    return result.concat(item, Array.isArray(item.children) ? addRoutes(item.children) : []);
  }, []);
}

let menuList = JSON.parse(localStorage.getItem("menuList")).filter(item => item.activePath == getBasename());
let asyncRoutes = getAsyncRoutes(menuList[0].children, getBasename());

export { asyncRoutes };
